package service;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.encrypt.WxaBizDataCrypt;
import com.jfinal.wxaapp.api.WxaUserApi;

import common.kit.PropKits;
import enums.WxuserRole;
import model.Company;
import model.Servicer;
import model.Staff;
import model.User;
import model.Wxuser;

public class WxuserService extends BaseService {

	public Ret checkLogin(String token , String ip) {
		if (StrKit.isBlank(token)) {
			return Ret.create("isLogin" , false) ;
		}
		Wxuser wxuser = Wxuser.dao.findFirstByToken(token);
		if (null == wxuser || (!ip.equals(wxuser.getIp()) && !PropKits.isDevMode()) ) {
			return Ret.create("isLogin" , false) ;
		}
		wxuser.keep("name" , "mobile" , "role");
		return Ret.create("isLogin" , true);
    }
	
	public Ret login(String jsCode , String encryptedData , String iv , String ip) {
		WxaUserApi wxaUserApi = Duang.duang(WxaUserApi.class);
        JSONObject jsonObject = null ;
        try {
        	ApiResult apiResult = wxaUserApi.getSessionKey(jsCode);
    		String sessionKey = apiResult.getStr("session_key");
    		WxaBizDataCrypt dataCrypt = new WxaBizDataCrypt(sessionKey);
            String json = dataCrypt.decrypt(encryptedData, iv);
        	jsonObject = JSONObject.parseObject(json);
		} catch (Exception e) {
			e.printStackTrace();
			return Ret.create("state" , "codeInvalid");
		}
		String mobile = jsonObject.getString("purePhoneNumber");
		List<Wxuser> list = Wxuser.dao.findByMobile(mobile);
		if (list.size() == 0) {
			return fail("当前手机号未登记，请联系管理员");
		}
		if (list.size() > 1) {
			List<String> roles = new ArrayList<String>();
			for (Wxuser wxuser : list) {
				wxuser.setToken(StrKit.getRandomUUID());
				wxuser.setIp(ip);
				wxuser.update();
				if (roles.size() < 6) {
					String companyName = wxuser.getCompanyName() ;
					if (wxuser.isStaffRole()) {
						Staff staff = Staff.dao.findFirstByWxuser(wxuser);
						companyName = staff.getName() ;
					}
					if (wxuser.isMangerRole()) {
						User user = User.dao.findById(wxuser.getCompanyId());
						companyName = user.getContact() ;
					}
					String name = companyName + "("+  WxuserRole.getTitleByValue(wxuser.getRole()) +")" ;
					roles.add(name);
				}
				wxuser.keep("name","role","mobile","token");
			}
			return ok().set("needChooseRole" , true).set("list" , list).set("roles",roles);
		}
		Wxuser wxuser = list.get(0);
		wxuser.setToken(StrKit.getRandomUUID());
		wxuser.setIp(ip);
		wxuser.update();
		wxuser.keep("name","role","mobile","token");
		return ok().set("needChooseRole" , false).set("data",wxuser);
    }
	
	public Ret info(Wxuser wxuser) {
		if (wxuser.isCompanyRole()) {
			Company company = Company.dao.findById(wxuser.getCompanyId());
			Record data = company.toRecord();
			data.keep("name","mobile");
			data.set("role", wxuser.getRole());
			return Ret.create("data" , data);
		}
		if (wxuser.isMangerRole()) {
			User user = User.dao.findById(wxuser.getCompanyId());
			Record data = user.toRecord();
			data.keep("mobile");
			data.set("name", user.getContact());
			data.set("role", wxuser.getRole());
			return Ret.create("data" , data);
		}
		Servicer servicer = Servicer.dao.findById(wxuser.getCompanyId());
		Record data = servicer.toRecord();
		data.keep("name");
		data.set("mobile", wxuser.getMobile());
		data.set("role", wxuser.getRole());
		if (wxuser.isSeviserRole()) {
			return Ret.create("data" , data);
		}
		Staff staff = Staff.dao.findFirstByWxuser(wxuser);
		if (null != staff) {
			data.set("staffName", staff.getName());
		}
		return Ret.create("data" , data);
	}
}
